﻿Option Strict On

Imports KUeLib.Attachments
Imports KUeLib.Buchungen
Imports LibUtils.QuickEdit
Imports ExHandlerLib
Imports System.Drawing
Imports System.Windows.Forms
Imports MppKostenuebersicht.Formulare.Buchungen.Controls
Imports System.Runtime.InteropServices
Imports KUeLib.Data.ServiceDefinitions

Public Class BuchungDetailForm
    Inherits WeifenLuo.WinFormsUI.Docking.DockContent
    Implements LibMultiPlug.Core.Plugins.Interfaces.IFormOptions
    Implements LibMultiPlug.Core.Reporting.IReportable


    Private Const PROCESS_NAME As String = "buchungen"

    Private _buchungNew As Boolean
    Private _buchung As Buchung
    Private _buchungenService As BuchungenDataSerivce
    Private _positionenService As BuchungspositionenDataService
    Private _kategoienService As KategorienDataService
    Private _fileAttachmentService As FileAttachmentDataService
    Private _statusService As StatusDataService
    Private _vertragsService As VertragsDataService
    Private _errors As ErrorProviderManager
    Private _textBoxFormater As New TextBoxFormater
    Private _attachments As List(Of FileAttachment)
    Private _positionen As List(Of Positionen.Buchungsposition)

    Public Sub New()

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

        Dim serviceManager As KUeLib.Data.ServiceManager = KUeLib.Data.ServiceManager.GetInstance()

        _buchungenService = serviceManager.GetBuchungenDataService()
        _kategoienService = serviceManager.GetKategorienDataService()
        _fileAttachmentService = serviceManager.GetFileAttachmentDataService()
        _positionenService = serviceManager.GetBuchungspositionenDataService()
        _vertragsService = serviceManager.GetVertragDataService()
        _statusService = serviceManager.GetStatusDataService()

        Dim kategorien As List(Of KUeLib.Kategorien.Kategorie) = _
            _kategoienService.GetAlleKategorien()

        kategorien.Sort(New KUeLib.Kategorien.KategorieComparer())

        cbKategorie.DataSource = kategorien
        cbKategorie.DisplayMember = "DisplayText"
        cbKategorie.ValueMember = "Id"

        cbVertrag.DataSource = _vertragsService.GetVertraegeForComboBoxSelection()
        cbVertrag.DisplayMember = "Bezeichnung"
        cbVertrag.ValueMember = "Id"

        cbStatus.DataSource = _statusService.GetStatusForProcess(PROCESS_NAME)
        cbStatus.DisplayMember = "Bezeichnung"
        cbStatus.ValueMember = "Bezeichnung"

        _errors = New ErrorProviderManager
        'CoorpDesignLib.ControlFormater.GetInstance().RegisterControls(Me.Controls)

     

    End Sub

    Public ReadOnly Property Buchung As Buchung
        Get
            Return _buchung
        End Get
    End Property

    Public Overloads Sub Show(ByVal dockPanel As WeifenLuo.WinFormsUI.Docking.DockPanel, ByVal buchungId As Integer) Implements LibMultiPlug.Core.Reporting.IReportable.Show
        _buchung = _buchungenService.GetBuchungById(buchungId)
        If _buchung Is Nothing Then _
            Throw New NullReferenceException(String.Format("Eine Buchung mit der Id '{0}' existiert nicht.", buchungId.ToString()))
        BindContents()
        _buchungNew = False
        MyBase.Show(dockPanel)
    End Sub

    Public Overloads Sub Show(ByVal dockPanel As WeifenLuo.WinFormsUI.Docking.DockPanel)
        _buchung = New Buchung
        _buchungNew = True
        BindContents()
        SetPositionssumme()
        MyBase.Show(dockPanel)
    End Sub

    Private Sub BindContents()

        dtpBuchungsdatum.DataBindings.Clear()
        dtpWertstellungsdatum.DataBindings.Clear()
        tbKontostand.DataBindings.Clear()
        tbBeguenstigter.DataBindings.Clear()
        tbBemerkung.DataBindings.Clear()
        tbBetrag.DataBindings.Clear()
        tbBuchungstext.DataBindings.Clear()
        tbVwz1.DataBindings.Clear()
        tbVwz2.DataBindings.Clear()
        tbVwz3.DataBindings.Clear()
        tbVwz4.DataBindings.Clear()
        tbVwz5.DataBindings.Clear()
        tbVwz6.DataBindings.Clear()
        tbVwz7.DataBindings.Clear()
        tbVwz8.DataBindings.Clear()
        tbVwz9.DataBindings.Clear()
        tbVwz10.DataBindings.Clear()
        tbVwz11.DataBindings.Clear()
        tbVwz12.DataBindings.Clear()
        tbVwz13.DataBindings.Clear()
        tbVwz14.DataBindings.Clear()
        cbStatus.DataBindings.Clear()
        cbVertrag.DataBindings.Clear()
        cbKategorie.DataBindings.Clear()
        tbBemerkung.DataBindings.Clear()

        ' wenn die buchung leer ist das formular sperren und die bindung abbrechen
        If _buchung Is Nothing Then _
            Me.Enabled = False : Exit Sub

        Me.Text = String.Format("Buchungsdetails #{0}", _buchung.Id.ToString("000000"))

        lblHeader.Text = String.Format("Buchung #{0} (Konto {1})", _buchung.Id.ToString("000000"), _buchung.Konto)

        dtpBuchungsdatum.DataBindings.Add("Value", _buchung, "Buchungsdatum")
        _errors.RegisterControl(dtpBuchungsdatum, "Value")

        dtpWertstellungsdatum.DataBindings.Add("Value", _buchung, "Wertstellungsdatum")
        _errors.RegisterControl(dtpWertstellungsdatum, "Value")

        tbKontostand.DataBindings.Add("Text", _buchung, "Kontostand")
        tbKontostand.DataBindings("Text").FormattingEnabled = True
        _errors.RegisterControl(tbKontostand, "Text")
        AddHandler tbKontostand.DataBindings("Text").Format, AddressOf CoorpDesignLib.ControlFormater.FormatCurrencyEventHandler

        tbBetrag.DataBindings.Add("Text", _buchung, "Betrag")
        tbBetrag.DataBindings("Text").FormattingEnabled = True
        _errors.RegisterControl(tbBetrag, "Text")
        AddHandler tbBetrag.DataBindings("Text").Format, AddressOf CoorpDesignLib.ControlFormater.FormatCurrencyEventHandler

        tbBuchungstext.DataBindings.Add("Text", _buchung, "Buchungstext")
        tbBeguenstigter.DataBindings.Add("Text", _buchung, "Beguenstigter")

        _textBoxFormater.RegisterTextBox(tbBuchungstext)
        _textBoxFormater.RegisterTextBox(tbBeguenstigter)

        tbVwz1.DataBindings.Add("Text", _buchung, "Verwendungszweck0")
        _errors.RegisterControl(tbVwz1, "Text")

        tbVwz2.DataBindings.Add("Text", _buchung, "Verwendungszweck1")
        _errors.RegisterControl(tbVwz2, "Text")

        tbVwz3.DataBindings.Add("Text", _buchung, "Verwendungszweck2")
        _errors.RegisterControl(tbVwz3, "Text")

        tbVwz4.DataBindings.Add("Text", _buchung, "Verwendungszweck3")
        _errors.RegisterControl(tbVwz4, "Text")

        tbVwz5.DataBindings.Add("Text", _buchung, "Verwendungszweck4")
        _errors.RegisterControl(tbVwz5, "Text")

        tbVwz6.DataBindings.Add("Text", _buchung, "Verwendungszweck5")
        _errors.RegisterControl(tbVwz6, "Text")

        tbVwz7.DataBindings.Add("Text", _buchung, "Verwendungszweck6")
        _errors.RegisterControl(tbVwz7, "Text")

        tbVwz8.DataBindings.Add("Text", _buchung, "Verwendungszweck7")
        _errors.RegisterControl(tbVwz8, "Text")

        tbVwz9.DataBindings.Add("Text", _buchung, "Verwendungszweck8")
        _errors.RegisterControl(tbVwz9, "Text")

        tbVwz10.DataBindings.Add("Text", _buchung, "Verwendungszweck9")
        _errors.RegisterControl(tbVwz10, "Text")

        tbVwz11.DataBindings.Add("Text", _buchung, "Verwendungszweck10")
        _errors.RegisterControl(tbVwz11, "Text")

        tbVwz12.DataBindings.Add("Text", _buchung, "Verwendungszweck11")
        _errors.RegisterControl(tbVwz12, "Text")

        tbVwz13.DataBindings.Add("Text", _buchung, "Verwendungszweck12")
        _errors.RegisterControl(tbVwz13, "Text")

        tbVwz14.DataBindings.Add("Text", _buchung, "Verwendungszweck13")
        _errors.RegisterControl(tbVwz14, "Text")

        tbBemerkung.DataBindings.Add("Text", _buchung, "Bemerkung")
        _errors.RegisterControl(tbBemerkung, "Text")

        cbStatus.DataBindings.Add("SelectedValue", _buchung, "Status")
        _errors.RegisterControl(cbStatus, "SelectedValue")

        cbKategorie.DataBindings.Add("SelectedValue", _buchung, "KategorieId")
        _errors.RegisterControl(cbKategorie, "SelectedValue")

        cbVertrag.DataBindings.Add("SelectedValue", _buchung, "VertragId")
        _errors.RegisterControl(cbVertrag, "SelectedValue")

    End Sub

    Private Sub SetPositionssumme()
        Dim summe As Double = _positionenService.GetAufteilungssummeForBuchungs(_buchung.Id)
        tbAufteilungssumme.Text = summe.ToString((New System.Globalization.CultureInfo("de-DE").NumberFormat))
        If summe >= 0 Then
            tbAufteilungssumme.ForeColor = Color.Green
        Else
            tbAufteilungssumme.ForeColor = Color.Red
        End If
        tbAufteilungssumme.ReadOnly = True
    End Sub

    Private Sub InternalSave()
        If _buchungNew Then
            _buchung = _buchungenService.InsertBuchung(_buchung)
            BindContents()
            _buchungNew = False
        Else
            _buchungenService.UpdateBuchung(_buchung)
        End If

        For Each c As Control In flpPositionen.Controls
            CType(c, PositionControl).Save()
        Next
    End Sub

    Private Sub InitializeFiles()

        _attachments = _fileAttachmentService.GetAttachmentForProcess(_buchung.Id)
        lvAttachments.Items.Clear()

        For Each fa As FileAttachment In _attachments
            Dim lvi As ListViewItem = lvAttachments.Items.Add(fa.Bezeichnung)
            lvi.SubItems.Add(fa.Filename)
            lvi.SubItems.Add(fa.Datum.ToShortDateString())
        Next

    End Sub

    Private Sub NewFileAttachment()
        If Not _buchungNew Then
            Dim faf As New Formulare.Fileattachments.FileAttachmentForm
            faf.ShowDialog(_buchung.Id)
            InitializeFiles()
        End If
    End Sub

    Private Sub btnOpenFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenFile.Click
        Call OpenCurrentAttachment()
    End Sub

    Private Sub OpenCurrentAttachment()
        If lvAttachments.SelectedIndices.Count > 0 Then
            _fileAttachmentService.FillBinary(_attachments(lvAttachments.SelectedIndices(0)))

            _attachments(lvAttachments.SelectedIndices(0)).StartAsProcess()

        End If
    End Sub

    Private Sub TpDateien_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles tpDateien.Enter
        InitializeFiles()
        RaiseEvent OptionsChanged(Me, Nothing)
    End Sub

    Private Sub InitializePositionen()
        Me.flpPositionen.Controls.Clear()
        _positionen = _positionenService.GetPositionenForProcess(_buchung.Id)

        For Each position As Positionen.Buchungsposition In _positionen
            Dim pc As New PositionControl(position)
            flpPositionen.Controls.Add(pc)
        Next
    End Sub

    Private Sub TpAufteilungen_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles tpAufteilungen.Enter
        InitializePositionen()
        RaiseEvent OptionsChanged(Me, Nothing)
    End Sub

    Private Sub btnNewPosition_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewPosition.Click
        Call NewPosition()
    End Sub

    Private Sub NewPosition()
        Dim position As New Positionen.Buchungsposition
        Dim pc As PositionControl
        position.ParentId = _buchung.Id
        pc = New PositionControl(position)
        'pc.Width = 500
        'pc.Anchor = CType(AnchorStyles.Left + AnchorStyles.Right + AnchorStyles.Top, AnchorStyles)
        flpPositionen.Controls.Add(pc)
    End Sub

    Private Sub btnRefreshAufteilungen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefreshAufteilungen.Click
        InitializePositionen()
        RaiseEvent OptionsChanged(Me, Nothing)
    End Sub

    Private Sub TpInformation_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles tpInformation.Enter
        SetPositionssumme()
        RaiseEvent OptionsChanged(Me, Nothing)
    End Sub

    Private Sub btnDeletePosition_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeletePosition.Click
        For Each c As Control In flpPositionen.Controls
            If c.Focused Then
                CType(c, PositionControl).Delete()
                Exit Sub
            End If
            For Each childC As Control In c.Controls
                If childC.Focused Then _
                    CType(c, PositionControl).Delete() : Exit Sub
            Next
        Next
    End Sub

    Private Sub btnOpenVertrag_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenVertrag.Click
        If cbVertrag.SelectedItem IsNot Nothing Then
            Dim vf As New Formulare.Vertraege.VertragForm
            vf.Show(Me.DockPanel, CType(cbVertrag.SelectedItem, KUeLib.Vertraege.Vertrag).Id)
        End If
    End Sub

    'Public Shadows Sub BringToFront() Implements IDetailForm.BringToFront
    '    MyBase.BringToFront()
    'End Sub


    Private Sub lvAttachments_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvAttachments.SelectedIndexChanged
        RaiseEvent OptionsChanged(Me, Nothing)
    End Sub

    Private Sub BuchungDetailForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        '_script.AddObject("form", _buchungenService, True)
        '_script.Eval("MsgBox(form.DbDataService.ToString())")
    End Sub


    Private Sub cbVertrag_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbVertrag.TextChanged
        If cbVertrag.SelectedIndex = -1 Then
            _buchung.VertragId = Nothing
        End If
    End Sub

    Private Sub cbKategorie_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbKategorie.TextChanged
        If cbKategorie.SelectedIndex = -1 Then
            _buchung.KategorieId = Nothing
        End If
    End Sub
End Class